package me.zhengjie.modules.quartz.task;

import com.qiaofang.applet.common.util.RedisKeyUtil;
import com.qiaofang.applet.service.member.domain.Employee;
import com.qiaofang.applet.service.member.repository.EmployeeRepository;
import com.qiaofang.applet.service.member.service.EmployeeService;
import com.qiaofang.applet.service.member.service.dto.EmpFansAndExchangeDto;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class EmpFansAndExchangeCountTask {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private EmployeeRepository employeeRepository;


    public void run() {
        String taskKey = RedisKeyUtil.getTaskKey(this.getClass().getSimpleName());
        if (redisUtils.hasKey(taskKey)){
            return;
        }
        redisUtils.set(taskKey, "", 1, TimeUnit.HOURS);

        log.info("EmpFansAndExchangeCountTask run start");
        Map<String, EmpFansAndExchangeDto> dtoMap = employeeService.getFansAndExchangeCount();
        if (dtoMap == null || dtoMap.size() == 0){
            log.info("EmpFansAndExchangeCountTask run end");
            redisUtils.del(taskKey);
            return;
        }
        Set<String> employeeUniqueUuidSet = dtoMap.keySet();
        List<Employee> list = employeeRepository.findListByEmployeeUniqueUuidIn(new ArrayList<>(employeeUniqueUuidSet));
        for (Employee employee : list) {
            EmpFansAndExchangeDto dto = dtoMap.get(employee.getEmployeeUniqueUuid());
            if (dto == null){
                continue;
            }
            employee.setFocusByCount(dto.getFocusByCount());
            employee.setReceptionCount(dto.getReceptionCount());
        }
        if (!CollectionUtils.isEmpty(list)) {
            try {
                employeeRepository.saveAll(list);
            } catch (Exception e) {
                log.error("EmpFansAndExchangeCountTask run error", e);
            }
        }
        log.info("EmpFansAndExchangeCountTask run end");

        redisUtils.del(taskKey);
    }
}
